import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import router from '../router'

// 创建axios实例
const instance = axios.create({
  // 如果环境变量不存在，则使用一个默认的API基础URL
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    console.log('[Axios Interceptor] 请求拦截器触发，URL:', config.url);
    // 从localStorage获取token
    const token = localStorage.getItem('admin_token')
    
    if (token) {
      console.log('[Axios Interceptor] 从 localStorage 获取到 token:', token.substring(0,10) + '...');
      config.headers['Authorization'] = `Bearer ${token}`
      console.log('[Axios Interceptor] 设置 Authorization 请求头为:', config.headers['Authorization'].substring(0, 20) + '...');
    } else {
      console.warn('[Axios Interceptor] localStorage 中未找到 admin_token。');
    }
    console.log('[Axios Interceptor] 最终请求头:', config.headers);
    console.log('[Axios Interceptor] 请求完整URL:', config.baseURL + config.url);
    return config
  },
  error => {
    console.error('[Axios Interceptor] 请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const url = response.config.url;
    console.log(`[Axios Interceptor] 响应拦截器成功: ${url}, 状态: ${response.status}`);
    
    if (url.includes('/user')) {
      console.log(`[Axios Interceptor] 用户API响应数据:`, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        data: response.data,
        dataType: typeof response.data,
        hasBody: response.data && response.data.body ? "有body字段" : "无body字段",
        structure: response.data ? Object.keys(response.data).join(', ') : "空数据"
      });
    }
    
    return response;
  },
  error => {
    if (error.response) {
      console.error(`[Axios Interceptor] 请求错误: ${error.config.url}, 状态码: ${error.response.status}`, {
        status: error.response.status,
        statusText: error.response.statusText,
        message: error.message,
        data: error.response.data
      });
      
      // 处理401未授权错误
      if (error.response.status === 401) {
        console.warn('[Axios Interceptor] 收到401错误，执行登出和重定向。');
        try {
          const authStore = useAuthStore()
          // 清除登录状态
          authStore.logout()
          
          // 使用router进行导航，而不是直接修改window.location
          if (router.currentRoute.value.name !== 'login') {
            router.push({ name: 'login' })
          }
        } catch (piniaError) {
          console.error('[Axios Interceptor] 在处理401时操作 Pinia store 出错:', piniaError)
          // 如果router实例不可用，则强制跳转
          if (window.location.pathname !== '/login') {
             window.location.href = '/login'
          }
        }
      }
    } else if (error.request) {
      console.error('[Axios Interceptor] 请求发送但未收到响应', error.request);
    } else {
      console.error('[Axios Interceptor] 请求错误', error.message);
    }
    
    return Promise.reject(error);
  }
)

export default instance